package com.itfreer.power.service.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.power.dao.user.UserAuthenticationDao;
import com.itfreer.power.entity.user.UserAuthenticationEntity;
import com.itfreer.power.utils.PasswordEncoder;

/**
 * 定义用户认证信息管理类
 */
@Component("userAuthenticationService")
public class UserAuthenticationServiceBase implements UserAuthenticationService {

	@Autowired
	private UserAuthenticationDao userAuthenticationDao;

	@Autowired(required = false)
	private PasswordEncoder passwordEncoder;

	/**
	 * 获取实体
	 * 
	 * @param guid
	 *            唯一值
	 * @return
	 */
	public UserAuthenticationEntity getEntity(String guid) {
		return userAuthenticationDao.getEntity(guid);
	}

	/**
	 * 添加实体
	 * 
	 * @param entity 添加实体
	 * @return
	 */
	public UserAuthenticationEntity add(UserAuthenticationEntity entity) {
		if (entity != null) {
			if (entity.getPassword() == null || entity.getPassword().equals("")) {
				entity.setPassword("123456");
			}
			if (entity.getPassword().equals("******")) {
				entity.setPassword("123456");
			}
			if (passwordEncoder != null) {
				entity.setPassword(passwordEncoder.encode(entity.getPassword()));
			}
		}
		return userAuthenticationDao.add(entity);
	}

	/**
	 * 更新实体
	 * 
	 * @param guid
	 *            唯一值
	 * @param entity
	 *            实体
	 * @return
	 */
	public UserAuthenticationEntity update(UserAuthenticationEntity entity) {
		if (entity != null) {
			if (entity.getPassword() == null || entity.getPassword().equals("")) {
				entity.setPassword("123456");
			}
			// 说明没有修改
			if (entity.getPassword().equals("******")) {
				UserAuthenticationEntity oldUser = getEntity(entity.getUserid());
				entity.setPassword(oldUser.getPassword());
			} else {
				if (passwordEncoder != null) {
					entity.setPassword(passwordEncoder.encode(entity.getPassword()));
				}
			}
		}
		return userAuthenticationDao.update(entity);
	}
}